package xin.marcher.module.seller.controller;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xin.marcher.module.common.core.JsonResult;
import xin.marcher.module.common.exception.BaseBizException;
import xin.marcher.module.seller.cache.SellerInfoCache;
import xin.marcher.module.seller.domain.request.SellerInfoCacheRequest;

import javax.annotation.Resource;

/**
 * 平台级的卖家运营管理系统
 * 让运营人员可以对卖家信息进行管理, 通过点击按钮, 触发单机/分布式的把卖家数据从 db 里查出来
 */
@Slf4j
@RestController
@RequestMapping("/sellerCache")
public class SellerCacheController {

    @Resource
    private SellerInfoCache sellerInfoCache;

    /**
     * 单机预热 API
     * 背景: 人工调用 api 触发缓存预热
     *
     * @param request
     * @return
     */
    @PostMapping("/preheat")
    public JsonResult<Boolean> preheatSellerCache(@RequestBody SellerInfoCacheRequest request) {
        try {
            Boolean result = sellerInfoCache.preheatSellerCache(request);
            return JsonResult.buildSuccess(result);
        } catch (BaseBizException baseBizException) {
            log.error("biz error: request={}", JSON.toJSONString(request), baseBizException);
            return JsonResult.buildError(baseBizException.getMessage());
        } catch (Exception e) {
            log.error("system error: request={}", JSON.toJSONString(request), e);
            return JsonResult.buildError(e.getMessage());
        }
    }

    /**
     * 分布式/集群 预热 API
     * 背景: 人工调用 api 触发缓存预热
     *
     * @param request
     * @return
     */
    @PostMapping("shardingPreheat")
    public JsonResult<Boolean> shardingPreheatSellerCache(@RequestBody SellerInfoCacheRequest request) {
        try {
            Boolean result = sellerInfoCache.shardingPreheatSellerCache(request);
            return JsonResult.buildSuccess(result);
        } catch (BaseBizException baseBizException) {
            log.error("biz error: request={}", JSON.toJSONString(request), baseBizException);
            return JsonResult.buildError(baseBizException.getMessage());
        } catch (Exception e) {
            log.error("system error: request={}", JSON.toJSONString(request), e);
            return JsonResult.buildError(e.getMessage());
        }
    }
}
